package jnpf.service.impl;

import jnpf.entity.*;
import jnpf.mapper.TagMangeMapper;
import jnpf.model.template.TagVO;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.tagmange.*;
import cn.hutool.core.util.ObjectUtil;
import jnpf.util.GeneraterSwapUtil;

import java.lang.reflect.Field;
import com.baomidou.mybatisplus.annotation.TableField;
import jnpf.model.QueryModel;
import java.util.stream.Collectors;
import jnpf.base.model.ColumnDataModel;
import jnpf.util.UserProvider;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.util.*;
import java.util.*;
import jnpf.base.UserInfo;
import jnpf.permission.entity.UserEntity;
/**
 *
 * tagMange
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-04-12
 */
@Service
public class TagMangeServiceImpl extends ServiceImpl<TagMangeMapper, TagMangeEntity> implements TagMangeService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private TagService tagService;

    @Override
    public List<TagMangeEntity> getList(TagMangePagination tagMangePagination){
        return getTypeList(tagMangePagination,tagMangePagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<TagMangeEntity> getTypeList(TagMangePagination tagMangePagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
        List<List<String>> intersectionList =new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? TagMangeConstant.getAppColumnData() : TagMangeConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total=0;
        int tagMangeNum =0;
        QueryWrapper<TagMangeEntity> tagMangeQueryWrapper=new QueryWrapper<>();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp ="";
        if (ObjectUtil.isNotEmpty(tagMangePagination.getSuperQueryJson())){
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList  = new ArrayList<>();
            String queryJson = tagMangePagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<TagMangeEntity> tagMangeSuperWrapper = new QueryWrapper<>();
            tagMangeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(tagMangeSuperWrapper,TagMangeEntity.class,queryJson,"0"));
            int tagMangeNum1 = tagMangeSuperWrapper.getExpression().getNormal().size();
            if (tagMangeNum1>0){
                List<String> tagMangeList =this.list(tagMangeSuperWrapper).stream().map(TagMangeEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(tagMangeList);
                intersectionSuperList.add(tagMangeList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if(superOp.equalsIgnoreCase("and")){
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            }else{
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp ="";
        if (ObjectUtil.isNotEmpty(ruleJson)){
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList  = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<TagMangeEntity> tagMangeSuperWrapper = new QueryWrapper<>();
            tagMangeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(tagMangeSuperWrapper,TagMangeEntity.class,ruleJson,"0"));
            int tagMangeNum1 = tagMangeSuperWrapper.getExpression().getNormal().size();
            if (tagMangeNum1>0){
                List<String> tagMangeList =this.list(tagMangeSuperWrapper).stream().map(TagMangeEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(tagMangeList);
                intersectionRuleList.add(tagMangeList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if(ruleOp.equalsIgnoreCase("and")){
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            }else{
                allRuleIDlist = allRuleList;
            }
        }
    boolean pcPermission = false;
    boolean appPermission = false;
    if(isPc && pcPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object tagMangeObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(tagMangeQueryWrapper,TagMangeEntity.class,tagMangePagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(tagMangeObj)){
        return new ArrayList<>();
        } else {
        tagMangeQueryWrapper = (QueryWrapper<TagMangeEntity>)tagMangeObj;
        if( tagMangeQueryWrapper.getExpression().getNormal().size()>0){
        tagMangeNum++;
        }
        }
    }
    }
    if(!isPc && appPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object tagMangeObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(tagMangeQueryWrapper,TagMangeEntity.class,tagMangePagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(tagMangeObj)){
        return new ArrayList<>();
        } else {
        tagMangeQueryWrapper = (QueryWrapper<TagMangeEntity>)tagMangeObj;
        if( tagMangeQueryWrapper.getExpression().getNormal().size()>0){
        tagMangeNum++;
        }
        }


    }
    }
        if(isPc){
            if(ObjectUtil.isNotEmpty(tagMangePagination.getTagType())){
            tagMangeNum++;

        List<String> idList = new ArrayList<>();
        try {
        String[][] tagType = JsonUtil.getJsonToBean(tagMangePagination.getTagType(),String[][].class);
        for(int i=0;i<tagType.length;i++){
        if(tagType[i].length>0){
        idList.add(JsonUtil.getObjectToString(Arrays.asList(tagType[i])));
        }
        }
        }catch (Exception e1){
        try {
        List<String> tagType = JsonUtil.getJsonToList(tagMangePagination.getTagType(),String.class);
        if(tagType.size()>0){
            idList.addAll(tagType);
        }
        }catch (Exception e2){
        idList.add(String.valueOf(tagMangePagination.getTagType()));
        }
        }
        tagMangeQueryWrapper.lambda().and(t->{
        idList.forEach(tt->{
        t.like(TagMangeEntity::getTagType, tt).or();
        });
        });

            }

            if(ObjectUtil.isNotEmpty(tagMangePagination.getCreateUserId())){
            tagMangeNum++;

        tagMangeQueryWrapper.lambda().eq(TagMangeEntity::getCreateUserId,tagMangePagination.getCreateUserId());

            }

            if(ObjectUtil.isNotEmpty(tagMangePagination.getCreateTime())){
            tagMangeNum++;

                List CreateTimeList =  JsonUtil.getJsonToList(tagMangePagination.getCreateTime(),String.class);
                    Long fir = Long.valueOf(String.valueOf(CreateTimeList.get(0)));
                    Long sec = Long.valueOf(String.valueOf(CreateTimeList.get(1)));

                    tagMangeQueryWrapper.lambda().ge(TagMangeEntity::getCreateTime, new Date(fir))
                    .le(TagMangeEntity::getCreateTime, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));


            }

            if(ObjectUtil.isNotEmpty(tagMangePagination.getTagId())){
            tagMangeNum++;

                String value = tagMangePagination.getTagId() instanceof List ?
                    JsonUtil.getObjectToString(tagMangePagination.getTagId()) :
                    String.valueOf(tagMangePagination.getTagId());
                tagMangeQueryWrapper.lambda().like(TagMangeEntity::getTagId,value);

            }

        }
        if(!isPc){
            if(ObjectUtil.isNotEmpty(tagMangePagination.getTagId())){
            tagMangeNum++;

                String value = tagMangePagination.getTagId() instanceof List ?
                    JsonUtil.getObjectToString(tagMangePagination.getTagId()) :
                    String.valueOf(tagMangePagination.getTagId());
                tagMangeQueryWrapper.lambda().like(TagMangeEntity::getTagId,value);

            }

        }
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total>0){
            if (intersection.size()==0){
                intersection.add("jnpfNullList");
            }
            tagMangeQueryWrapper.lambda().in(TagMangeEntity::getId, intersection);
        }
    //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)){
            if (allSuperIDlist.size()==0){
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            tagMangeQueryWrapper.lambda().and(t->t.in(TagMangeEntity::getId, finalAllSuperIDlist));
        }
    //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)){
            if (allRuleIDlist.size()==0){
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            tagMangeQueryWrapper.lambda().and(t->t.in(TagMangeEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if(StringUtil.isEmpty(tagMangePagination.getSidx())){
            tagMangeQueryWrapper.lambda().orderByDesc(TagMangeEntity::getTagId);
        }else{
            try {
                String sidx = tagMangePagination.getSidx();
                String[] strs= sidx.split("_name");
                TagMangeEntity tagMangeEntity = new TagMangeEntity();
                Field declaredField = tagMangeEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                tagMangeQueryWrapper="asc".equals(tagMangePagination.getSort().toLowerCase())?tagMangeQueryWrapper.orderByAsc(value):tagMangeQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<TagMangeEntity> page=new Page<>(tagMangePagination.getCurrentPage(), tagMangePagination.getPageSize());
                IPage<TagMangeEntity> userIPage=this.page(page, tagMangeQueryWrapper);
                return tagMangePagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<TagMangeEntity> list = new ArrayList();
                return tagMangePagination.setData(list, list.size());
            }
        }else{
            return this.list(tagMangeQueryWrapper);
        }
    }
    @Override
    public TagMangeEntity getInfo(String id){
        QueryWrapper<TagMangeEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(TagMangeEntity::getId,id);
        return this.getOne(queryWrapper);
    }
    @Override
    public void create(TagMangeEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String id, TagMangeEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(TagMangeEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(TagMangeForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id="";
        String countRecover = "";
        if (isUp){
            id = form.getId();
        }
        //主表字段验证
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param tagMangeForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(TagMangeForm tagMangeForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        tagMangeForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(TagMangeConstant.getFormData(),tagMangeForm),TagMangeForm.class);
        TagMangeEntity entity = JsonUtil.getJsonToBean(tagMangeForm, TagMangeEntity.class);

        if(isSave){
            String mainId =  RandomUtil.uuId() ;
        entity.setCreateUserId(userInfo.getUserId());
        entity.setCreateTime(DateUtil.getNowDate());
            entity.setId(mainId);
        }else{
        entity.setCreateUserId(userInfo.getUserId());
        entity.setCreateTime(DateUtil.getNowDate());
        }
        this.saveOrUpdate(entity);

    }

    @Override
    public List<TagVO> getTagVOList(String entityId) {
        // 1. 查询符合条件的TagMangeEntity列表(子表)
        QueryWrapper<TagMangeEntity> tagMangeEntityQueryWrapper = new QueryWrapper<>();
        tagMangeEntityQueryWrapper.lambda().eq(TagMangeEntity::getEntityId, entityId);
        List<TagMangeEntity> tagMangeEntityList = this.list(tagMangeEntityQueryWrapper);

        if(tagMangeEntityList.isEmpty()){
            return new ArrayList<>();
        }

        // 2. 提取所有tagId用于查询父表信息
        List<String> tagIds = tagMangeEntityList.stream()
                .map(TagMangeEntity::getTagId)
                .collect(Collectors.toList());

        // 3. 批量查询父表(tag表)信息
        Map<String, TagEntity> tagMap = tagService.listByIds(tagIds).stream()
                .collect(Collectors.toMap(TagEntity::getId, tag -> tag));

        // 4. 组合结果
        List<TagVO> result = new ArrayList<>();
        for (TagMangeEntity tagMange : tagMangeEntityList) {
            TagEntity tag = tagMap.get(tagMange.getTagId());
            if (tag != null) {
                TagVO vo = new TagVO();
                // 设置父表字段
                vo.setTagId(tag.getId());
                vo.setTagType(tag.getTagType());
                vo.setIsPre(tag.getIsPre());
                vo.setEntityId("1");
                vo.setTagName(tag.getName());
                // 设置子表字段
                vo.setEntityId(tagMange.getEntityId());
                result.add(vo);
            }
        }
        return result;
    }
}
